package org.su.webadapter;

import org.su.generalmvc.core.InitialContext;
import org.su.generalmvc.entity.FormFile;
import org.su.generalmvc.util.FormFileArray;
import org.su.generalmvc.util.StringArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;


/**
 * 默认的文件上传请求包装。
 * 重写了参数获取方法
 * 实现了文件获取方法
 * @author yangchuan createtime:2012-6-2下午4:14:46
 *
 */
public class DefaultMultipartHttpServletRequest extends
		AbstractMultipartHttpServletRequest {

	protected static final Log logger = LogFactory.getLog(DefaultMultipartHttpServletRequest.class);
	private Map<String, StringArray> params = null;
	
	private Map<String,FormFileArray> formFileParams = null;
	
	public DefaultMultipartHttpServletRequest(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getParameter(String name) {
		
		StringArray values = params.get(name);
		if (values != null) {
			return (values.getSize() > 0 ? values.get(0) : null);
		}
		return getRequest().getParameter(name);
	}

	@Override
	public Enumeration<String> getParameterNames() {
		List<String> set = new ArrayList<String>();
		Set<String> set1 = params.keySet();
		for(String key:set1){
			set.add(key);
		}
		Set<String> keys = formFileParams.keySet();
		for(String key:keys){
			set.add(key);
		}
		//set.addAll(formFileParams.keySet());
		return  Collections.enumeration(set);
	}

	@Override
	public String[] getParameterValues(String name) {
		StringArray values = params.get(name);
		if (values != null) {
			return values.toArray();
		}
		return getRequest().getParameterValues(name);
		
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		return getRequest().getParameterMap();
	}

	
	
	public FormFile[] getFormFiles(String name){
		FormFileArray values = formFileParams.get(name);
		if (values != null) {
			return values.toArray();
		}
		return null;
	}
	
	public FormFile getFormFile(String name){
		FormFile[] files = getFormFiles(name);
		if(files != null && files.length>0){
			return files[0];
		}
		return null;
	}
	
	
	
	@Override
	public void initializeMultipart(ServletFileUpload upload) {
		initParams(upload);
	}

	public void initParams(ServletFileUpload upload){
		
		HttpServletRequest request = getRequest();
		params = new HashMap<String, StringArray>();
		formFileParams = new HashMap<String, FormFileArray>();
		try {
			List<?> fileItems = upload.parseRequest(request);
			Iterator<?> iter = fileItems.iterator();
			String encoding = InitialContext.getInstance().getContext().getConfig().getEncoding();
			StringArray temp = null;
			FormFileArray tempFiles = null;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					temp = params.get(item.getFieldName());
					if(temp != null){
						temp.add(item.getString(encoding));
					}else{
						temp = new StringArray();
						temp.add(item.getString(encoding));
					}
					params.put(item.getFieldName(), temp);
				} else {
					String fieldName = item.getFieldName();
					FormFile formFile = null;
					String fileName = item.getName();
					if (StringUtils.isNotBlank(fileName)) {
						formFile = new FormFile();
						int c = fileName.lastIndexOf("\\");
						int cc = fileName.lastIndexOf("/");
						int i = c > cc ? c : cc;
						formFile.setName(fileName.substring(i + 1));
						formFile.setSize(item.getSize());
						formFile.setInputStream(item.getInputStream());
						formFile.setContentType(item.getContentType());
					}
					
					tempFiles = formFileParams.get(fieldName);
					if(tempFiles != null){
						tempFiles.add(formFile);
					}else{
						tempFiles = new FormFileArray();
						tempFiles.add(formFile);
					}
					formFileParams.put(fieldName, tempFiles);
				}
			}
		} catch (IOException e) {
			logger.error(e);
		} catch (FileUploadException e) {
			logger.error(e);
		}
	}
	
	
}
